package com.bdweb.mokuai;

import java.io.OutputStream;
import java.net.Socket;

public class startThreadSocket {
    private Thread thread;//循环发送心跳包的线程
    private Socket socket;//与服务器建立连接的socket对象
    private OutputStream outputStream;//输出流，用于发送心跳

    public void startThreadSocket() {
        try {
            if(!socket.getKeepAlive()) socket.setKeepAlive(true);//true，若长时间没有连接则断开
           if(!socket.getOOBInline())socket.setOOBInline(true);//true,允许发送紧急数据，不做处理
            outputStream = socket.getOutputStream();//获得socket的输出流
            final String socketContent = "[这里为与服务器协商的特殊字符串，用于识别是发送的心跳信息]" + "\n";
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep( 1000);//20s发送一次心跳
                            outputStream.write(socketContent.getBytes("UTF-8"));
                            outputStream.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
